package com.zhong.loadingview;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;

import com.zhong.loadingview.view.LoadingLayout;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.zhong.loadingview.view.LoadingLayout.LOAD_FAILURE_STATE;
import static com.zhong.loadingview.view.LoadingLayout.LOAD_SUCCESS_STATE;
import static com.zhong.loadingview.view.LoadingLayout.NET_ERROR_STATE;
import static com.zhong.loadingview.view.LoadingLayout.NULL_DATA_STATE;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.loading_layout_id)
    protected LoadingLayout loadingLayout;

    @BindView(R.id.image_view)
    protected ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);
    }

    @OnClick({R.id.success_btn,R.id.net_error_btn,R.id.load_failure_btn,R.id.null_data_btn})
    protected void onClick(View view){
        switch (view.getId()){
            case R.id.success_btn:
                simulateHttpRequest(LOAD_SUCCESS_STATE);
                break;
            case R.id.load_failure_btn:
                simulateHttpRequest(LOAD_FAILURE_STATE);
                break;
            case R.id.net_error_btn:
                simulateHttpRequest(NET_ERROR_STATE);
                break;
            case R.id.null_data_btn:
                simulateHttpRequest(NULL_DATA_STATE);
                break;
        }
    }

    Handler handler = new Handler();

    /**
     * 模拟网络访问
     * @param state 访问状态
     */
    private void simulateHttpRequest(final int state){
        loadingLayout.showLoading();

        imageView.setBackground(null);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(state == LOAD_SUCCESS_STATE){
                    imageView.setBackgroundResource(R.mipmap.ic_launcher);
                }

                loadingLayout.refreshView(state, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        simulateHttpRequest(state);
                    }
                });
            }
        }, 2000);
    }
}
